package com.shs.sys.controller;

import com.shs.sys.common.ActiverUser;
import com.shs.sys.common.ResultObj;
import com.shs.sys.common.WebUtils;
import com.shs.sys.entity.Loginfo;
import com.shs.sys.mapper.LoginfoMapper;
import com.shs.sys.service.LoginfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Author: jxm
 * @Description: 登录控制器
 * @Date: 2020/4/9 14:16
 * @Version: 1.0
 */
@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private LoginfoService loginfoService;



    /**
     * 登录
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping("login")
    public ResultObj login(String userName,String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try {
            subject.login(token);
            ActiverUser activerUser = (ActiverUser)subject.getPrincipal();
            WebUtils.getSession().setAttribute("user",activerUser.getUser());
            //记录登录日志
            Loginfo loginfo = new Loginfo();
            loginfo.setLoginname(activerUser.getUser().getName()+"-"+activerUser.getUser().getLoginname());
            loginfo.setLoginip(WebUtils.getRequest().getRemoteAddr());
            loginfo.setLogintime(new Date());
            loginfoService.save(loginfo);
            return ResultObj.LOGIN_SUCCESS;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return ResultObj.LOGIN_ERROR_PASS;
        }
    }
}
